/**
 * Created by ren on 30/03/2017.
 */
"use strict";
import * as json from './jsonFormat'
import Toast from 'react-native-root-toast';
import PageUtil from '../utils/PageUtil';
import Login from '../views/Login'
let pageUtil = new PageUtil();
import SplashScreen from 'react-native-splash-screen'
export function post(apiUrl, body, ...params) {
  return new Promise((resolve, reject) => {
    fetch(apiUrl, {
      method: 'post',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: json.formatString(body)
    }).then((response) => {
      return response.json()
    })
      .then((responseJson) => {
        console.log(responseJson);
        if (responseJson['success']) {
          if (responseJson.data) {
            resolve(responseJson.data);
          } else {
            resolve()
          }
        } else {
          if (responseJson['code'] === 501 || responseJson['code'] === 500) {
            SplashScreen.hide();
            pageUtil.resetTo(Login)
          }
          toast(responseJson.message)
          if (params) {
            params.map(param => {
              if (param.isBack) {
                reject(responseJson);
              }
            })
          }
        }
      }).catch((error) => {
      toast('网络异常！')
      if (params) {
        params.map(param => {
          if (param.isBack) {
            reject(error);
          }
        })
      }
    });
  })
}
export function get(apiUrl, body) {
  console.log(apiUrl);
  return new Promise((resolve, reject) => {
    fetch(apiUrl + '?' + json.formatString(body), {
      method: 'get',
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      }
    }).then((response) => {
      return response.json()
    })
      .then((responseJson) => {
        console.log(responseJson);
        if (responseJson['success']) {
          resolve(responseJson.data);
        } else {
          if (responseJson['code'] === 501) {
            pageUtil.resetTo(Login)
          }
          toast(responseJson.message)
        }
      }).catch(() => {
      toast('网络异常！')
    });
  })
}
export function remove(apiUrl, body) {
  console.log(apiUrl);
  return new Promise((resolve, reject) => {
    fetch(apiUrl + '?' + json.formatString(body), {
      method: 'delete',
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      }
    }).then((response) => response.json())
      .then((responseJson) => {
        console.log(responseJson);
        if (responseJson['success']) {
          if (responseJson.data) {
            resolve(responseJson.data);
          } else {
            resolve()
          }
        } else {
          if (responseJson['code'] === 501) {
            pageUtil.resetTo(Login)
          }
          toast(responseJson.message)
        }
      }).catch(() => {
      toast('网络异常！')
    });
  })
}
export function toast(msg) {
  Toast.show(msg)
}

